package domain

import (
	"github.com/lab-online/internal/shared/code"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
	"github.com/lab-online/pkg/auth"
)

func (d *Domain) UpdateUser(authEntity auth.AuthEntity, user entity.UserEntity) (entity.UserEntity, error) {
	savedUser, dbErr := d.repository.GetUserByUsername(user.GetUsername())
	if dbErr != nil {
		return nil, code.ErrorPicker(dbErr, code.DatabaseUserNotFound, constant.RESTErrUserNotFound)
	}

	if !savedUser.CanHandleUser(authEntity, false) {
		return nil, constant.RESTErrNoPermissionPatch
	}

	if user.GetRole() != 0 && !authEntity.IsAdmin() {
		return nil, constant.RESTErrNoPermissionPatch
	}

	savedUser.Update(entity.WithName(user.GetName()), entity.WithRole(user.GetRole()))
	return d.repository.SaveUser(savedUser)
}
